var fs = require("fs")
var os = require("os");
const process = require('process');
// process.exit(1);
const csvParser = require('csv-parser');
const sourceFile = './csv/fill.csv';
const tagetFile = './csv/filter.csv';
const { keys } =  require('../config/key.js');

console.log('----- filter start -----');
fs.appendFileSync(tagetFile, keys.join(',') + os.EOL);
let ele = {};
fs.createReadStream(sourceFile)
  .pipe(csvParser())
  .on('data', (data) => {
    if (!ele.time) {
      ele = Object.assign({}, data);
      writeFile(tagetFile, data);
    } else {
      let time = subTime(data.time, ele.time);
      if (time >= 15) {
        ele = Object.assign({}, data);
        writeFile(tagetFile, data);
      }
    }
  })
  .on('end', () => {
    console.log('----- filter end -----');
  });


function writeFile(filePath, data){
    let arr = [];
    keys.forEach(val=>{
      arr.push(data[val]);
    })
    const text = arr.join(',')
	  fs.appendFileSync(filePath, text + os.EOL);
}

function subTime(time1, time2) {
  return ((new Date(time1) - new Date(time2)) / 1000).toFixed(0);
}
